package com.wdcg.activity;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.wdcg.R;
import com.wdcg.ar.AugmentedReality;
import com.wdcg.ar.AugmentedView;
import com.wdcg.ar.SensorsActivity;
import com.wdcg.ar.camera.CameraSurface;
import com.wdcg.ar.data.ARData;
import com.wdcg.ar.data.LocalDataSource;
import com.wdcg.ar.ui.Marker;
import com.wdcg.ar.utils.VerticalSeekBar;
import com.wdcg.ar.utils.VerticalTextView;
import com.wdcg.model.access.DwarfAccess;
import com.wdcg.model.dao.DwarfDescription;
import com.wdcg.utils.GameLogic;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;


/**
 * This class extends the AugmentedReality and is designed to be an example on
 * how to extends the AugmentedReality class to show multiple data sources.
 * 
 * @author Justin Wetherell <phishman3579@gmail.com>
 */
public class ARGameActivity  extends SensorsActivity implements OnTouchListener {
	
	public final static String PARAM_DWARF_ID = "DwarfID";    
	private Context context;
	private Handler handler;

    protected static WakeLock wakeLock = null;
    protected static CameraSurface camScreen = null;
    protected static AugmentedView augmentedView = null;
    protected static LinearLayout pointsLayout = null;
    protected static LinearLayout clockLayout = null;
    protected static TextView points=null;
    protected static TextView timer=null;

    private DwarfDescription dwarfDesc;
    
    public static boolean ui_portrait = false;  // Defaulted to LANDSCAPE use  
    public static boolean showRadar = false;
    public static boolean showZoomBar = false;
    public static boolean useRadarAutoOrientate = false;
    public static boolean useMarkerAutoRotate = false;
    public static boolean useDataSmoothing = true;
    public static boolean useCollisionDetection = false; // defaulted OFF

    private Timer clock;
    private int time;
    
    protected static final int DIALOG_TIMEOUT= 0;
	
	private List<Marker> listOfMarkers;
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context=this;
        
        dwarfDesc=DwarfAccess.getDwarfDescriptionForDwarfId(getIntent().getIntExtra(PARAM_DWARF_ID, -1));
		
        handler = new Handler(){
        	
        	public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                case DIALOG_TIMEOUT:
                	
                	final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
		        	
		        	alertDialog.setTitle(getString(R.string.ar_game_fail_alert_title));
					alertDialog.setMessage(getString(R.string.ar_game_fail_alert_message));
					alertDialog.setButton(Dialog.BUTTON_NEUTRAL,getString(R.string.game_alert_close_button), new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialog, int which) {
							alertDialog.dismiss();	
							finish();
						}
					});
					try {
					alertDialog.show();
					}
					catch(Exception e){
						   // WindowManager$BadTokenException will be caught and the app would not display 
						   // the 'Force Close' message
						 }
                }

        	};
        };
        
        camScreen = new CameraSurface(this);
        setContentView(camScreen);

        augmentedView = new AugmentedView(this);
        augmentedView.setOnTouchListener(this);
        LayoutParams augLayout = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        addContentView(augmentedView, augLayout);

        pointsLayout = new LinearLayout(this);
        pointsLayout.setOrientation(LinearLayout.HORIZONTAL);
        pointsLayout.setPadding(5, 5, 5, 5);
        pointsLayout.setBackgroundColor(Color.TRANSPARENT);

        points = new TextView(this);
        
        points.setTextSize(17);
        points.setTextColor(Color.WHITE);
        LinearLayout.LayoutParams pointTextParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        pointTextParams.gravity = Gravity.RIGHT;
        pointsLayout.addView(points, pointTextParams);
        
        clockLayout = new LinearLayout(this);
        clockLayout.setOrientation(LinearLayout.HORIZONTAL);
        clockLayout.setPadding(5, 5, 5, 5);
        clockLayout.setBackgroundColor(Color.TRANSPARENT);

        
        timer = new TextView(this);
        
        timer.setTextSize(17);
        timer.setTextColor(Color.WHITE);
        LinearLayout.LayoutParams timerTextParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        timerTextParams.gravity = Gravity.LEFT;
        clockLayout.addView(timer, timerTextParams);
        

        FrameLayout.LayoutParams frame2LayoutParams = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.TOP);
        addContentView(clockLayout, frame2LayoutParams);
        
        FrameLayout.LayoutParams frameLayoutParams = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM);
        addContentView(pointsLayout, frameLayoutParams);



        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
   
        
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void onResume() {
        super.onResume();

        wakeLock.acquire();
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void onPause() {
        super.onPause();

        wakeLock.release();
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    public void onSensorChanged(SensorEvent evt) {
        super.onSensorChanged(evt);

        if (evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER || evt.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            augmentedView.postInvalidate();
        }
    }

    

   
    /**
     * {@inheritDoc}
     */
    
    public boolean onTouch(View view, MotionEvent me) {
        if (me.getAction() != MotionEvent.ACTION_DOWN) return false;

        // See if the motion event is on a Marker
        for (Marker marker : ARData.getMarkers()) {
            if (marker.handleClick(me.getX(), me.getY())) {
                markerTouched(marker);
                return true;
            }
        }

        return super.onTouchEvent(me);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onStart() {
        super.onStart();

       Location last = ARData.getCurrentLocation();
       LocalDataSource localData = new LocalDataSource(this.getResources(), last);
       listOfMarkers = localData.getMarkers();
       points.setText("Pozostałych krasnalów: "+listOfMarkers.size());
       
       time=30;
       
       startCounting();
       
       ARData.addMarkers(listOfMarkers);
    }

   
    protected void markerTouched(Marker marker) {
        
    	listOfMarkers.remove(marker);
        ARData.clearMarkerList();
        ARData.addMarkers(listOfMarkers);
        
        points.setText("Pozostałych krasnalów: "+listOfMarkers.size());
        
        if(listOfMarkers.size()==0){
        	
        	final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        	
        	alertDialog.setTitle(getString(R.string.ar_game_success_alert_title));
			alertDialog.setMessage(getString(R.string.ar_game_success_alert_message));
			alertDialog.setButton(Dialog.BUTTON_NEUTRAL,getString(R.string.game_alert_close_button), new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();	
					GameLogic.setDwarfUnlocked(dwarfDesc.getDwarf());
					GameLogic.getMoreDwarfsVisible();
					finish();
				}
			});
			try {
				alertDialog.show();
				}
				catch(Exception e){
					   // WindowManager$BadTokenException will be caught and the app would not display 
					   // the 'Force Close' message
					 }
        }
    }

    private void startCounting(){
		clock = new Timer();
		clock.schedule(new TimerTask(){

			@Override
			public void run() {
				if(time <= 0){
					cancel();
					handler.sendEmptyMessage(DIALOG_TIMEOUT);
					
				}			
				if(time <10){
					setNewTime("00:0"+time);
				}
				else{
					setNewTime("00:"+time);
					
				}
				
				time--;
			}}, 0, 1000);
	}
    
    private void setNewTime(final String newTime){
    	runOnUiThread(new Runnable(){

			public void run() {
				timer.setText("Pozostały czas: "+newTime);
			}
			
		});
    }
    
}
